package gwtool.backend;

import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class CryptoController {

	public static String hashPWSHA(String password) {

		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA-256");
		} catch (NoSuchAlgorithmException e) {
		}
		md.update(password.getBytes());
		byte byteData[] = md.digest();

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
		}
		return sb.toString();
	}

	public byte[] genAESPassFromUserPass(String seed) {

		byte[] hash = hashPWSHA(seed).getBytes();
		byte[] aesPass = new byte[16];
		for (int i = 0; i < aesPass.length; i++) {
			aesPass[i] = hash[i];
		}
		return aesPass;
	}

	public Cipher getEncryptCipher(byte[] pass) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {

		SecretKeySpec specKey = new SecretKeySpec(pass, "AES");
		Cipher encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		encryptCipher.init(Cipher.ENCRYPT_MODE, specKey);
		return encryptCipher;
	}

	public Cipher getDecryptCipher(byte[] pass) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {

		SecretKeySpec specKey = new SecretKeySpec(pass, "AES");
		Cipher decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		decryptCipher.init(Cipher.DECRYPT_MODE, specKey);
		return decryptCipher;
	}
}
